﻿/****************
* Authored by Zhuo "Wizcas" Chen
* 2018 © Wubi.fun all rights reserved
*****************/

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

public class Game : MonoBehaviour
{
    static Game _instance;
    public static Game instance { get { return _instance ?? (_instance = FindObjectOfType<Game>()); } }

    public float deadline = 300;
    public bool isStarted { get; private set; }
    public bool isTimeChallenge { get; private set; }

    bool _isPaused;
    public bool isPaused
    {
        get { return _isPaused; }
        set { _isPaused = value; Time.timeScale = isPaused ? 0 : 1;
            onPauseChanged.Invoke(_isPaused);
        }
    }
    public float timeRemaining { get; private set; }
    public bool isInTutorial;

    public UnityEvent onGameLaunch;
    public UnityEvent onGameStart;
    public ScoreEvent onGameEnd;
    public PauseEvent onPauseChanged;

    private void Awake()
    {
        Init();
    }

    void Init()
    {
        isPaused = false;
        isStarted = false;
        onGameLaunch.Invoke();
    }

    public void StartGame(bool isTimeChallenge)
    {
        World.instance.Clear();
        ResManager.instance.Clear();
        this.isTimeChallenge = isTimeChallenge;
        timeRemaining = deadline;
        isStarted = true;
        onGameStart.Invoke();
    }

    public void EndGame()
    {
        isStarted = false;
        onGameEnd.Invoke(ResManager.instance.CalculateScore());
    }

    public void ToMainMenu()
    {
        Init();
    }

    public void Update()
    {
        if (Input.GetKeyDown(KeyCode.Escape))
        {
            isPaused = true;
        }

        if (isTimeChallenge && isStarted)
        {
            timeRemaining -= Time.deltaTime;
            if (timeRemaining < 0)
            {
                EndGame();
            }
        }
    }
}

[System.Serializable]
public class ScoreEvent : UnityEvent<int> { }
[System.Serializable]
public class PauseEvent : UnityEvent<bool> { }